const { query } = require('express');
const express = require('express');
const router = express.Router();
//导入模型
const queryPromise = require('../model/query-promise.js')
//接口

router.get('/cate', async (req, res) => {
    let sql = `select * from category where is_show = 1`;
    let result = await queryPromise(sql)
    res.json(result)
})

//获取首页分页的文章
router.get('/article', async (req, res) => {
    let { page = 1, pagesize = 3 } = req.query;
    //起始位置 当前页面--乘以每页显示的条数
    let offset = (page - 1) * pagesize;
    let sql = `select t1.*,t2.cate_name from masterpieces1 t1 left join category t2 on t1.cat_id = t2.cate_id 
                where is_delete = 0  limit ${offset}, ${pagesize}`
    // let sql = `select * from masterpieces1 where is_delete = 0 limit ${offset}, ${pagesize}`;
    let result = await queryPromise(sql)
    res.json(result)
})

//获取分类页面文章
router.get('/catelist', async (req, res) => {
    const { cate_id } = req.query;
    const sql = `SELECT t1.*,t2.cate_name,t3.username from 
                masterpieces1 t1 LEFT JOIN category t2 on t1.cat_id = t2.cate_id 
                LEFT JOIN users t3 on t1.author = t3.user_id WHERE t1.Audit_status = 1 and t1.cat_id = ${cate_id}`
    let results = await queryPromise(sql)
    results.map((item) => {
        const { add_date } = item;
        item.add_date = add_date ? moment(add_date).format('YYYY-MM-DD HH:mm:ss') : '未添加'
        return item;
    })
    res.json(results)
})

//获取文章详情
router.get('/detail', async (req, res) => {
    let { id } = req.query
    id = parseInt(id)
    id = isNaN(parseInt(id)) ? 0 : parseInt(id);
    let sql = `select t1.cate_name,t2.* from category t1 left join masterpieces1 t2 on t1.cate_id =t2.cat_id  where t2.id= ${id}`;
    let result = await queryPromise(sql)
    console.log(result);
    res.json(result[0] || {})
})

router.get('*', (req, res) => {
    res.json({ message: "404" })
})

module.exports = router;